﻿using System.Data;
using System.Web.Mvc;
using NHibernate;
using Ornament.NHibernates;

namespace Ornament.Web.Mvc
{
    public class NHibernateFilterAttribute : ActionFilterAttribute, IExceptionFilter
    {
        private readonly bool _enabled;

        public NHibernateFilterAttribute(bool enabled)
        {
            Order = 0;
            _enabled = enabled;
            IsolationLevel = IsolationLevel.ReadCommitted;
        }

        private ITransaction _tras;
        public NHibernateFilterAttribute()
            : this(true)
        {
            Order = 0;
        }

        public bool Transaction { get; set; }

        public IsolationLevel IsolationLevel { get; set; }

        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            if (_enabled)
            {

                SessionManager.Instance.IniSession();
            }
            if (Transaction)
            {
                _tras = SessionManager.Instance.CurrentSession.BeginTransaction(IsolationLevel);
            }
        }
        public override void OnResultExecuted(ResultExecutedContext filterContext)
        {
            SessionManager.Instance.CleanUp();
        }

        public void OnException(ExceptionContext filterContext)
        {
            if (_tras != null)
            {
                _tras.Rollback();
                _tras = null;
            }
        }
    }
}